package com.are.manejadores;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.are.entidades.Roles;
import com.are.odisea.db;

public class ManejadorRoles {
	private db conexion;
	private Roles rol;
	
	public db getConexion() {
		return conexion;
	}
	public Roles getRol() {
		return rol;
	}
	public void setRol(Roles rol) {
		this.rol = rol;
	}
	public void setConexion(db conexion) {
		this.conexion = conexion;
	}
	public ManejadorRoles(db conexion, Roles rol) {
		super();
		this.conexion = conexion;
		this.rol = rol;
	}
	public ManejadorRoles(db conexion) {
		super();
		this.conexion = conexion;
	}
	
	
	public boolean add(String descripcion) throws SQLException {
		boolean result = false;
		String sql = "insert into roles (descripcion) values (?)";
		java.sql.PreparedStatement pst = conexion.getConnection()
				.prepareStatement(sql);
		pst.setString(1, descripcion);
		if (conexion.Update(pst) > 0) {
			conexion.Commit();
			result = true;
		}
		return result;
	}

	public boolean remove(String id) throws SQLException {
		boolean result = false;
		String sql = "delete from roles where id=?";
		java.sql.PreparedStatement pst = conexion.getConnection()
				.prepareStatement(sql);
		pst.setString(1, id);
		if (conexion.Update(pst) > 0) {
			conexion.Commit();
			result = true;
			
		}
		return result;
	}

	public boolean update(String id,String descripcion) throws SQLException {
		boolean result = false;
		String sql = "update roles set descripcion=? where id=?";
		java.sql.PreparedStatement pst = conexion.getConnection()
				.prepareStatement(sql);
		pst.setString(1,descripcion);
		pst.setString(2, id);
		if (conexion.Update(pst) > 0) {
			conexion.Commit();
			result = true;
		}
		return result;
	}
	
	public ArrayList<Roles> list() throws SQLException {
		ArrayList<Roles> lista = new ArrayList<Roles>();
		String sql = "select * from roles order by descripcion";
		ResultSet rs = conexion.Query(sql);
		while (rs.next()) {
			Roles rol = new Roles();
			rol.setId(rs.getString("id"));
			rol.setDescripcion(rs.getString("descripcion"));
			lista.add(rol);
		}
		rs.close();
		return lista;
	}
	
	public boolean Find(String id) throws SQLException {
		boolean result = false;
		String sql = "select * from roles where id = ?";
		java.sql.PreparedStatement pst = conexion.getConnection()
				.prepareStatement(sql);
		pst.setString(1,id);
		ResultSet rs = conexion.Query(pst);
		if (rs.next()) {
			rol = new Roles();
			rol.setId(rs.getString("id"));
			rol.setDescripcion(rs.getString("descripcion"));
			result = true;
		}
		rs.close();
		
		return result;
		
	}

}
